package Cantella::DJabberd::Role::CurrentUser;

use Reaction::Role;

role CurrentUser which {

  has 'current_user' =>
    (
     init_arg => undef,
     reader => 'current_user',
     writer => '_set_current_user',
     predicate => 'has_current_user',
     clearer => '_clear_current_user',
     trigger_adopt('current_user'),
  );

  has 'current_user_callback' => (
    is => 'rw'
  );

  implements check_roles => as {
    my $self = shift;
    confess "no current_user" unless $self->has_current_user;
    $self->current_user->check_roles( @_ );
  };

  implements adopt_current_user => as {
    my ($self) = @_;
    if (my $cb = $self->current_user_callback) {
      $cb->($self->current_user);
    }
  };

  after '_clear_current_user' => sub {
    my ($self) = @_;
    if (my $cb = $self->current_user_callback) {
      $cb->(undef);
    }
  };

};

1;
